package cn.usaiot.chat.video.videochat.call;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.usb.UsbDevice;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.serenegiant.usb.USBMonitor;

import org.webrtc.EglBase;
import org.webrtc.PeerConnection;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import cn.iotnova.rtc.WebrtcPeer;
import cn.usaiot.chat.video.videochat.R;

/**
 * Created by zengyongheng on 2020.
 * 悬浮控件为Button
 */

public class FloatingWindowService extends Service implements USBMonitor.OnDeviceConnectListener {
    public static boolean isStarted = false;

    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;

    //private Button button;
    FrameLayout frameLayoutMain;

    WebrtcActivity activity;

    Button button;
    WebrtcPeer peer1;

    private EglBase rootEglBase;
    private List<PeerConnection.IceServer> peerIceServers = new ArrayList<>();


    private void initVideos() {
        rootEglBase = EglBase.create();
    }

    private void getIceServers() {
        PeerConnection.IceServer peerIceServer = PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer();
        peerIceServers.add(peerIceServer);
    }


    /*
    public void onConnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock, boolean createNew) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                camera = new UVCCamera();
                camera.open(ctrlBlock);
                try {
                    camera.setPreviewSize(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, UVCCamera.FRAME_FORMAT_MJPEG);
                } catch (final IllegalArgumentException e) {
                    try {
                        camera.setPreviewSize(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, UVCCamera.DEFAULT_PREVIEW_MODE);
                    } catch (final IllegalArgumentException e1) {
                        camera.destroy();
                        camera = null;
                    }
                }
                camera.setPreviewDisplay(svVideoRender.getHolder());
                camera.setFrameCallback(WebrtcUsbCapturer.this, UVCCamera.PIXEL_FORMAT_NV21);
                camera.startPreview();
            }
        });
    }
     */

    private void startForeground() {
        String CHANNEL_ONE_ID = "com.snail.labaffinity";
        String CHANNEL_ONE_NAME = "Channel One";
        NotificationChannel notificationChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            assert manager != null;
            manager.createNotificationChannel(notificationChannel);
            startForeground(1, new NotificationCompat.Builder(this, CHANNEL_ONE_ID).build());
        }
    }


    private Executor executor = Executors.newSingleThreadExecutor();
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("进入服务1", "进入服务1");

        initVideos();
        getIceServers();

        startForeground();

        isStarted = true;
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        int height = windowManager.getDefaultDisplay().getHeight();

        layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.width = width;
        layoutParams.height = height;
        layoutParams.x = 0;
        layoutParams.y = 0;

        activity = WebrtcActivity.activity;

        executor.execute(new Runnable() {
            @Override
            public void run() {
                usbMonitor = new USBMonitor(WebrtcActivity.applicationContext, FloatingWindowService.this);
                usbMonitor.register();
            }
        });
        //peer1 = new WebrtcPeer();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("进入服务2", "进入服务2");

        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("进入服务3", "进入服务3");
        showFloatingWindow();
        return super.onStartCommand(intent, flags, startId);
    }

    private void showFloatingWindow() {

        //ThreadUtils.joinUninterruptibly();
        //https://www.jianshu.com/p/5902d4953ed9?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
        //org.webrtc.VideoTrack


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断系统版本
            //if (Settings.canDrawOverlays(this)) {
            if (true) {
                /*
                button = new Button(getApplicationContext());
                button.setText("我是个button窗口");
                button.setBackgroundColor(Color.BLUE);
                windowManager.addView(button, layoutParams);

                button.setOnTouchListener(new FloatingOnTouchListener());
                */
                Toast.makeText(activity, "FloatingWindowService", Toast.LENGTH_SHORT).show();

                frameLayoutMain = (FrameLayout)View.inflate(getApplicationContext(), R.layout.float_view,null);
                windowManager.addView(frameLayoutMain, layoutParams);
                button = frameLayoutMain.findViewById(R.id.button);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        peer1.close();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                });
                //SurfaceViewRenderer videoView = (SurfaceViewRenderer) frameLayoutMain.findViewById(R.id.gl_surface_view1);
                peer1 = new WebrtcPeer(activity);
                peer1.startPeer("car", rootEglBase, frameLayoutMain, R.id.gl_surface_view1, R.id.gl_surface_view2, WebrtcActivity.applicationContext, peerIceServers);
            }
        } else {
            /*
            button = new Button(getApplicationContext());
            button.setText("我是个button窗口");
            button.setBackgroundColor(Color.BLUE);
            windowManager.addView(button, layoutParams);

            button.setOnTouchListener(new FloatingOnTouchListener());
             */
            frameLayoutMain = (FrameLayout)View.inflate(this, R.layout.float_view,null);
            windowManager.addView(frameLayoutMain, layoutParams);
            button = frameLayoutMain.findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });
            //SurfaceViewRenderer videoView = (SurfaceViewRenderer) frameLayoutMain.findViewById(R.id.gl_surface_view1);
            peer1 = new WebrtcPeer(activity);
            peer1.startPeer("car", rootEglBase, frameLayoutMain, R.id.gl_surface_view1, R.id.gl_surface_view2, WebrtcActivity.applicationContext, peerIceServers);
        }
    }


    private USBMonitor usbMonitor;
    @Override
    public void onAttach(UsbDevice device) {

    }

    @Override
    public void onDettach(UsbDevice device) {

    }

    @Override
    public void onConnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock, boolean createNew) {

    }

    @Override
    public void onDisconnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock) {

    }

    @Override
    public void onCancel(UsbDevice device) {

    }



}
